package com.bawei.monthdemo2207a.month01.local

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageInfo
import android.os.Environment
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AddCircle
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.Button
import androidx.compose.material3.Checkbox
import androidx.compose.material3.Divider
import androidx.compose.material3.FabPosition
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil.compose.AsyncImage
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.FileUtils
import java.io.File

/**
 * 作者：赵亮
 * 时间：2024/12/27 12:08
 * 功能：
 */
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun LocalAppPage(navController: NavController = rememberNavController()) {

    val list = remember {
        SnapshotStateList<PackageInfo>()
    }

    /**
     * 选中的应用
     */
    var selected by remember {
        mutableStateOf(mutableSetOf<PackageInfo>())
    }

    /**
     * 一键卸载按钮是否可用
     */
    var isEnable by remember {
        mutableStateOf(false)
    }

    val context = LocalContext.current
    val packageManager = context.packageManager

    LaunchedEffect(key1 = "") {
        val installedPackages = packageManager.getInstalledPackages(0)
        list.addAll(installedPackages)
    }

    Scaffold(floatingActionButton = {
        Button(enabled = isEnable, onClick = {
            // 卸载选中的app
            selected.forEach {
                AppUtils.uninstallApp(it.packageName)
            }
        }) {
            Text(text = "一键卸载")
        }
    }, floatingActionButtonPosition = FabPosition.Center) {
        Column(modifier = Modifier.padding(top = 24.dp)) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(horizontal = 15.dp)
            ) {
                Icon(modifier = Modifier.clickable {
                    navController.popBackStack()
                }, imageVector = Icons.Default.ArrowBack, contentDescription = null)
                Text(text = "应用卸载", modifier = Modifier.weight(1f))
                Icon(imageVector = Icons.Default.MoreVert, contentDescription = null)
            }

            // 内存统计
            val activityManager =
                context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            Row(verticalAlignment = Alignment.Bottom) {
                Text(
                    text = "${ConvertUtils.byte2FitMemorySize(memoryInfo.availMem)}",
                    fontSize = 22.sp
                )
                Divider(
                    modifier = Modifier
                        .width(1.dp)
                        .height(15.dp)
                )
                Text(text = "${ConvertUtils.byte2FitMemorySize(memoryInfo.totalMem)}")
            }

            Box(modifier = Modifier.fillMaxWidth()) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(30.dp)
                        .background(color = Color.Gray, shape = RoundedCornerShape(10.dp))
                ) {

                }
                Box(
                    modifier = Modifier
                        .width(20.dp)
                        .height(30.dp)
                        .background(
                            color = Color.Green,
                            shape = RoundedCornerShape(topStart = 10.dp, bottomStart = 10.dp)
                        )
                ) {

                }
            }

            LazyColumn(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                items(list) {
                    Row {
                        AsyncImage(
                            model = it.applicationInfo.loadIcon(packageManager),
                            contentDescription = null
                        )
                        Column(modifier = Modifier.weight(1f)) {
                            Text(text = it.applicationInfo.loadLabel(packageManager).toString())
                            Text(text = "${FileUtils.getSize(File(it.applicationInfo.publicSourceDir))} | 从未使用")
                        }
                        Checkbox(checked = selected.contains(it), onCheckedChange = { check ->
                            if (check) {
                                selected = (selected + it) as MutableSet<PackageInfo>
                            } else {
                                selected = (selected - it) as MutableSet<PackageInfo>
                            }
                            if (selected.size > 0) {
                                isEnable = true
                            } else {
                                isEnable = false
                            }
                            Log.i(
                                "TAG",
                                "LocalAppPage: ${check}${selected}${selected.size}${
                                    selected.contains(it)
                                }"
                            )
                        })
                    }
                }
            }
        }
    }

}

@Preview
@Composable
fun LocalAppPagePreview() {
    LocalAppPage()
}

